//引入模块
const { PRIORITY_HIGH } = require('constants');
const express = require('express');
const mysql = require('../mysql');

//创建路由对象
let r = express.Router();

//用户登录
r.get('/v1/login/:uname&:upwd',(req,res)=>{
    let body = req.params;
    //执行sql命令
    mysql.query('select * from xz_user where uname=? and upwd=?',[body.uname,body.upwd],(err,result)=>{
        if(err) throw err;
        if(result.length != 0){
            return res.send('1');
        }
        res.send('0');
    });
});

//用户列表
r.get('/v1/list',(req,res)=>{
    mysql.query('select * from xz_user',(err,result)=>{
        if(err) throw err;
        if(result.length != 0){
            return res.send(result);
        }
        res.send('0');
    });
});

//用户模糊查询
r.get('/v1/search/:uname',(req,res)=>{
    let body = req.params;

    mysql.query('select * from xz_user where uname like ?',[`%${body.uname}%`],(err,result)=>{
        if(err) throw err;
        if(result.length != 0){
            return res.send(result);
        }
        res.send('0');
    });
});

//用户删除
r.delete('/v1/del/:uid',(req,res)=>{
    let id = req.params.uid;
    // console.log(id);
    mysql.query('delete from xz_user where uid=?',[id],(err,result)=>{
        if(err) throw err;
        if(result.affectedRows != 0){
            return res.send('1');
        }
        res.send('0');
    });
});

//用户根据id搜索
r.get('/v1/searchById/:uid',(req,res)=>{
    let id = req.params.uid;

    mysql.query('select * from xz_user where uid=?',[id],(err,result)=>{
        if(err) throw err;
        if(result.length != 0){
            return res.send(result);
        }
        res.send('0');
    });
});

//用户修改
r.put('/v1/update',(req,res)=>{
    let body = req.body;
    
    let sql = 'update xz_user set ? where uid=?';
    mysql.query(sql,[body,body.uid],(err,result)=>{
        if(err) throw err;
        if(result.affectedRows != 0){
            return res.send('1');
        }
        res.send('0');
    });
});

//用户名判断是否重复
r.get('/v1/getUname/:uname',(req,res)=>{
    let name = req.params.uname;

    mysql.query('select * from xz_user where uname=?',[name],(err,result)=>{
        if(err) throw err;
        if(result.length != 0){
            return res.send('1');
        }
        res.send('0');
    });
});

//用户注册
r.post('/v1/reg',(req,res)=>{
    let body = req.body;

    mysql.query('insert into xz_user set ?',[body],(err,result)=>{
        if(err) throw err;
        if(result.affectedRows != 0){
            return res.send('1');
        }
        res.send('0');
    });
});

//导出对象
module.exports = r;